package com.itheima.socket.udp.demo03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReceiveThread implements Runnable {

    @Override
    public void run() {

        try {

            // 1. 创建DatagramSocket对象
            DatagramSocket datagramSocket = new DatagramSocket(9999) ;

            while(true) {

                // 2. 创建数据包对象
                byte[] bytes = new byte[1024] ;
                int length = bytes.length ;
                DatagramPacket datagramPacket = new DatagramPacket(bytes , length) ;

                // 3. 接收数据
                datagramSocket.receive(datagramPacket) ;

                // 4. 解析数据
                byte[] data = datagramPacket.getData();
                int len = datagramPacket.getLength();

                // 获取发送端的ip地址信息
                InetAddress inetAddress = datagramPacket.getAddress();

                // 输出
                System.out.println(inetAddress.getHostAddress() + "说：" + new String(data , 0 , len , "UTF-8"));

            }

        }catch (Exception e) {
            e.printStackTrace();
        }

    }


}
